package com.superme.repository;

import org.springframework.data.jpa.domain.Specification;


import javax.persistence.criteria.*;

/*
该类定义person的查询条件
需要继承Specification<>
 */

public class PersonSpecification<PersonEntity> extends SpecificationBase implements Specification<PersonEntity> {
    public PersonSpecification() {
        this.name = null;
        this.nickname = null;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public PersonSpecification(String name, String nickname) {
        this.name = name;
        this.nickname = nickname;
    }

    /*
        定义查询字段
         */
    private String name;

    private String nickname;


    @Override
    public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
        //这遍取的是类中的私有变量
        Path<String> namePath = root.get("name");
        Path<String> nicknamePath = root.get("nickname");
        // 连接查询条件, 不定参数，可以连接0..N个查询条件
        Predicate p = null;
        Predicate pName = cb.like(namePath, "%" + this.name + "%");
        p = SetAnsCondition(p, cb, this.name, pName);
        Predicate pNickname = cb.like(nicknamePath, "%" + this.nickname + "%");
        p = SetAnsCondition(p, cb, this.nickname, pNickname);
        /*
        SetCondition ( p,cb,this.name,pName);函数相当于做以下的事情
        if (this.name != null)
        {
            Predicate pName = cb.like(namePath, "%"+this.name+"%");
            if(p!=null)
            {
                p = cb.and(pName,p);
            }
            else
            {
                p = pName;
            }
        }
        */
        //p = cb.and(cb.like(nicknamePath, "%"+this.nickname+"%"), p);
        //这里可以设置任意条查询条件
        query.where(p);
        //设置排序字段,如果不分页可以考虑在这里设置排序，也可以
        query.orderBy(cb.asc(root.get("name")), cb.asc(root.get("nickname")));
        return null;
    }
}
